// pages/order-details/order-details.js
var common = require("../../utils/public.js") //引入public.js脚本
var time = require("../../utils/time.js");
var api = require('../../utils/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numTime:0,
    number:0,
    orderCode:'',
    list:[],
    newTime: true,
    showMore:false,
    sh:false,
    num:0,//总商品数量
    orderDetailsEntityList:[],
    status:['待付款','待配送','已发货','已收货','待评价','已结束','退货中','已退货','取消'],//支付状态
    payType: ['配送到店-在线支付','配送到店-货到付款', '现场自提-在线支付','现场自提-货到付款'],//支付方式
    time:0,
    jbShow: false,
    times:0,
    userMess:{},//用户信息
    mortgage:0,
    jb:0,
    // 订单过期时间
    payovertime: 0,
    payovertimeStr: 0,
  },
  
  //超过两个商品 点击显示全部
  show: common.throttleFunc(function (e) {
    let that = this
    let userMess = wx.getStorageSync("userMess")
    that.setData({
      userMess:userMess
    })
    let orderDetailsEntityList = that.data.orderDetailsEntityList
    let showMore = that.data.showMore
    if (showMore == false) {
      if (orderDetailsEntityList.length > 2) {
        for (var i = 0; i < orderDetailsEntityList.length; i++) {//遍历数组 给数组元素加上隐藏
          orderDetailsEntityList[i].showCar = true;
        }
      } else {
        for (var i = 0; i < orderDetailsEntityList.length; i++) {//遍历数组 给数组元素加上隐藏
          orderDetailsEntityList[i].showCar = true;
        }
      }
      showMore = !showMore
      that.setData({
        orderDetailsEntityList: orderDetailsEntityList,
        showMore: showMore
      })
    } else {
      showMore = !showMore
      for (var i = 0; i < that.data.orderDetailsEntityList.length; i++) {
        orderDetailsEntityList[i].showCar = false
      }
      orderDetailsEntityList[0].showCar=true
      orderDetailsEntityList[1].showCar = true
      that.setData({
        orderDetailsEntityList: orderDetailsEntityList,
        showMore: showMore
      })
    }

  }),
  // 跳转评价
  pingjia: common.throttleFunc(function (e) {
    let that=this
    let index = e.currentTarget.dataset.index//下标
    let goodsId = this.data.orderDetailsEntityList[index].goodsId
    let orderCode=this.data.orderCode
    api.checkEval({
      goodsId,
      orderCode
    }).then(res=>{
      if (res.result){
        if(res.object==0){
          let goodsDetailsId = this.data.orderDetailsEntityList[index].goodsDetailsId//商品id
          let goodsPic = this.data.orderDetailsEntityList[index].goodsPic//图片连接
          let amount = this.data.orderDetailsEntityList[index].amount//数量
          let orderDetailsId = this.data.orderDetailsEntityList[index].id//订单id
          let specDesc = this.data.orderDetailsEntityList[index].specDesc//规格
          let goodsName = this.data.orderDetailsEntityList[index].goodsName//商品名
          let price = this.data.orderDetailsEntityList[index].receivePrice//单价 

          wx.navigateTo({
            url: '/pages/pingjia/pingjia?orderCode=' + that.data.orderCode + '&goodsDetailsId=' + goodsDetailsId + '&goodsPic=' + goodsPic + '&amount=' + amount + '&orderDetailsId=' + orderDetailsId + '&specDesc=' + specDesc + '&goodsName=' + goodsName + '&goodsId=' + goodsId,
          })
        } else if (res.object == 1){
          wx.showToast({
            title: '您已经评价过本商品!',
            icon: "none",
            duration: 1000
          })
        }
      }
    })
  }),
  // 跳转退货
  tuihuo: common.throttleFunc(function (e) {
    const type = wx.getStorageSync('type')
    if (type==0) {
      const authFunction = wx.getStorageSync('authFunction')
      const index = authFunction.indexOf("2")
      if(index == -1) {
        wx.showToast({
          title: '暂无权限',
          icon: "none"
        })
        return
      } 
    }
    let that=this
    if (that.data.list.createtime) {
    } else {
    }
    let index = e.currentTarget.dataset.index//下标
    let goodsDetailsId=this.data.orderDetailsEntityList[index].goodsDetailsId//商品id
    let goodsPic=this.data.orderDetailsEntityList[index].goodsPic//图片连接
    let amount=this.data.orderDetailsEntityList[index].amount//数量
    let orderDetailsId=this.data.orderDetailsEntityList[index].id//订单id
    let specDesc = this.data.orderDetailsEntityList[index].specDesc//规格
    let goodsName = this.data.orderDetailsEntityList[index].goodsName//商品名
    let ticketShareAmount = this.data.orderDetailsEntityList[index].ticketShareAmount||0
    let price = (this.data.orderDetailsEntityList[index].actualPrice - ticketShareAmount)/amount 
    //单价
    let actualPrice = this.data.orderDetailsEntityList[index].actualPrice//实收金额
    api.verification({
      orderDetailsId: orderDetailsId,
      orderCode: this.data.orderCode
    }).then(res=>{
      if (res.result) {
        if (res.code != 444) {
          wx.navigateTo({
            url: '/pages/tuihuo/tuihuo?orderCode=' + that.data.orderCode + '&goodsDetailsId=' + goodsDetailsId + '&goodsPic=' + goodsPic + '&amount=' + amount + '&orderDetailsId=' + orderDetailsId + '&specDesc=' + specDesc + '&goodsName=' + goodsName + '&price=' + price + '&actualPrice=' + actualPrice,
          })
        } else {
          wx.showToast({
            title: '您的订单正在处理中!',
            icon: "none",
            duration: 1000
          })
        }
      }else{
        if (res.code == 444) {
          wx.showToast({
            title: '您的订单正在处理中!',
            icon: "none",
            duration: 1000
          })
        } else if (res.code == 300){
          wx.showToast({
            title: '您的订单超过24小时!',
            icon: "none",
            duration: 1000
          })
        } else if (res.code == 222){
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000
          })
        }
      }
    })
    
    
  }),
  // btn: 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

   let that=this
    that.setData({
      orderCode: options.orderCode,
    })
    

    

  },
  //选择是否选择金币
  btnJb: function () {
    this.setData({
      jbShow: !this.data.jbShow,

    })
  },
  //确认收货
  btnPay:function(){
    const type = wx.getStorageSync('type')
    if (type==0) {
      const authFunction = wx.getStorageSync('authFunction')
      const index = authFunction.indexOf("1")
      if(index == -1) {
        wx.showToast({
          title: '暂无权限',
          icon: "none"
        })
        return
      } 
    }
    let that = this
    console.log(that.data.list.payType);
    // if (that.data.list.payType==1){
      wx.showModal({
        title: '确认收货',
        content: '是否确认收货？',
        success: function (res) {
          if (res.cancel) {

          } else if (res.confirm) {
            api.isReceipt({
              orderCode: that.data.orderCode
            }).then(res => {
              if (res.result) {
                wx.showToast({
                  title: '收货成功！',
                  icon: "none",
                  duration: 1000
                })
                setTimeout(function(){
                  wx.navigateBack({
                    data:1
                  })
                },1000)
              }
            })

          }
        }
      })
    // } 
    
  },
  //付款后撤销订单
  back: common.throttleFunc(function (e) {

    let that = this
    wx.showModal({
      title: '撤销订单',
      content: '是否撤销订单？',
      success: function (res) {
        if (res.cancel) {

        } else if (res.confirm) {
          api.orderRefund2({
            orderCode: that.data.orderCode,
            type: '0',
            reason: '',
          }).then(res=>{
            if(res.result){
              wx.showToast({
                title: '撤销订单成功！',
                icon: "none",
                duration: 1000,
                success: () => {
                  setTimeout(function () {
                    wx.navigateBack({
                      data: 1
                    })
                  }, 1000)
                }
              })
            }
          })

        }
      }
    })
  }),
  //待付款撤销订单
  back1: common.throttleFunc(function(e){
    let that=this
    api.orderRefund3({
      orderCode: that.data.orderCode,
      status:'8',
    }).then(res => {
      if(res.result){
        wx.showToast({
          title: '取消成功',
          icon: "none",
          duration: 1000
        })
        setTimeout(function () {
          wx.navigateBack({
            data: 1
          })
        }, 1000)
      } else if (res.code == 998){
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
      }
      
    })
  }),
  //付款
  pay:function(e){
  let that=this
      //货到付款 
      api.goToPay({
        orderCode: that.data.orderCode,
      }).then(res => {
        if (res.result) {
          wx.requestPayment({
            timeStamp: res.object.timeStamp,
            nonceStr: res.object.nonce_str,
            package: res.object.packageParams,
            signType: "MD5",
            paySign: res.object.sign,
            success: function (res) {
        
              if (res.errMsg == 'requestPayment:ok') {
                //成功回调
                api.payDirect({
                  orderCode: that.data.orderCode
                }).then(res => {
                  
                  if (res.result) {
                    wx.showToast({
                      title: '付款成功！',
                      icon: "none",
                      duration: 1000
                    })
                    setTimeout(function () {
                      wx.navigateBack({
                        data: 1
                      })
                    }, 1000)
                  }else{
                    wx.showToast({
                      title: res.result.msg,
                      icon: "none",
                      duration: 1000
                    })
                  }
                })
                // wx.navigateBack({
                //   data: 1
                // })
              }
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }else{
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }
      })
    

  },


  //货到付款
  btnPay1:function(){
    const type = wx.getStorageSync('type')
    if (type==0) {
      const authFunction = wx.getStorageSync('authFunction')
      const index = authFunction.indexOf("1")
      if(index == -1) {
        wx.showToast({
          title: '暂无权限',
          icon: "none"
        })
        return
      } 
    }
    let that=this
    if (that.data.jbShow == false) {

      api.deliveryAndOrder({
        orderCode: that.data.orderCode,
        isJb: that.data.jbShow == false ? 1 : 0
      }).then(res => {
        if (res.result) {
          if(res.code!=99){
            wx.showToast({
              title: res.object,
              icon: "none",
              duration: 1000
            })
          }else{
            wx.showToast({
              title: '收货成功！',
              icon: "none",
              duration: 1000
            })
            setTimeout(function () {
              wx.navigateBack({
                data: 1
              })
            }, 1000)
          }
         
        }
      })
    } else {
      console.log('货到付款 ');
      //货到付款 
      api.deliveryAndOrder({
        orderCode: that.data.orderCode,
        isJb: that.data.jbShow == false ? 1 : 0
      }).then(res => {
        if (res.result) {
          wx.requestPayment({
            timeStamp: res.object.timeStamp,
            nonceStr: res.object.nonce_str,
            package: res.object.packageParams,
            signType: "MD5",
            paySign: res.object.sign,
            success: function (res) {
              if (res.errMsg == 'requestPayment:ok') {
                //成功回调
                api.payDirect({
                  orderCode: that.data.orderCode
                }).then(res => {
                  if (res.result) {
                      if (res.code != 99) {
                        wx.showToast({
                          title: res.object,
                          icon: "none",
                          duration: 1000
                        })
                      } else {
                        wx.showToast({
                          title: '收货成功！',
                          icon: "none",
                          duration: 1000
                        })
                        setTimeout(function () {
                          wx.navigateBack({
                            data: 1
                          })
                        }, 1000)
                      }
                  }
                })
              }
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function () {
    let that = this
    let num = that.data.num
    let times = that.data.times
    api.get_cart({
      cityId: wx.getStorageSync("cityId"),
      userId: wx.getStorageSync("openId"),
      page: {}
    }).then(res => {

      that.setData({
        jb: res.data.object.balance
      })
      that.orderDetails()
    })
 
    
  },

  orderDetails: function () {
    let that = this
    api.getOrderInfoDetails({
      orderCode: that.data.orderCode
    }).then(res => {
      if (res.result) {
        let number=0
        if (res.object.orderDetailsEntityList.length > 2) {
          for (var i = 0; i < res.object.orderDetailsEntityList.length; i++) {//遍历数组 给数组元素加上隐藏
            res.object.orderDetailsEntityList[i].showCar = false;
          }
          res.object.orderDetailsEntityList[0].showCar = true
          res.object.orderDetailsEntityList[1].showCar = true
        } else {
          for (var i = 0; i < res.object.orderDetailsEntityList.length; i++) {//遍历数组 给数组元素加上隐藏
            res.object.orderDetailsEntityList[i].showCar = true;
          }
        }
        if (res.object.status == 4 || res.object.status == 3 || res.object.status == 5) {
          that.setData({
            sh: true
          })
        } else {
          that.setData({
            sh: false
          })
        }
        if (res.object.payovertime > Date.parse(new Date())) {
          res.object.newTime = false
          } else {
          res.object.newTime = true
          }
        for (var i = 0; i < res.object.orderDetailsEntityList.length; i++){
          number = res.object.orderDetailsEntityList[i].receivePrice +number
        }
        that.setData({
          orderDetailsEntityList: res.object.orderDetailsEntityList,
          list: res.object,
          time: time.formatTimeTwo(res.object.createtime * 1, 'Y/M/D h:m:s'),
          times: time.formatTimeTwo(res.object.createtime * 1 + 24 * 60 * 60 * 1000, 'Y/M/D'),
          number:number,
          payovertime: res.object.payovertime,
          jbShow: !res.object.isJb,
        })
        
        that.startTimer()
        that.mortgage()
       
      }
    })

  },

  //本次可抵用
  mortgage:function(){
    let that=this
    if (Number(that.data.jb) > Number(that.data.list.actualPrice)) {
      that.setData({
        mortgage: Number(that.data.list.actualPrice).toFixed(2)
      })
    } else if (Number(that.data.jb) <= Number(that.data.list.actualPrice)) {
      that.setData({
        mortgage: Number(that.data.jb).toFixed(2)
      })
    }
  },


  startTimer() {
    let now = Date.now()
    this.setData({
      payovertimeStr: time.formatTimeTwo(this.data.payovertime - now, 'm:s'),
    })
    this.timer = setInterval(() => {
      let now = Date.now()
      this.setData({
        payovertimeStr: time.formatTimeTwo(this.data.payovertime - now, 'm:s'),
        numTime: this.data.payovertime - now
      })
      if (this.data.payovertime - Date.now() >= 0 && this.data.payovertime - Date.now()<=1000) {
        clearInterval(this.timer)
        this.timer = null
        this.back1()
      }
    }, 1000)

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }

  },
  
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})